<script setup lang="ts">
import { ref, computed } from "vue";
import empty from "@visual/assets/empty.png";
import { convertStringToNumber } from "@visual/utils";

import ReTextTooltip from "../../../components/ReTextTooltip";

defineOptions({
  name: "middleTip"
});
const emits = defineEmits(["openCharline"]);
const props = withDefaults(
  defineProps<{
    contentList?: Array<any>;
    title?: string;
    code?: string;
    groupName?: string;
    curTreeData?: any;
  }>(),
  {
    contentList: () => [],
    curTreeData: () => {},
    title: "",
    code: "",
    groupName: ""
  }
);
function openCharline() {
  emits("openCharline");
}
// 文字宽度计算函数（完整支持字重、空格、斜体）
const calculateTextWidth = (() => {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  return (text, fontStyle = "14px Arial bold") => {
    // 确保字体样式包含字重（如 bold、normal）
    ctx.font = fontStyle;
    const metrics = ctx.measureText(text);

    // 使用实际边界框计算（更精准，尤其是斜体）
    const actualWidth = metrics.actualBoundingBoxLeft + metrics.actualBoundingBoxRight;

    // 若边界框不可用（某些浏览器），回退到 width
    return actualWidth > 0 ? actualWidth : metrics.width;
  };
})();

// 动态调整组件宽度的核心函数
const getDynamicWidth = ({ text, offset = 90, minWidth = 200, fontStyle, disableOffset = false }) => {
  // 保留文本中的空格（避免 trim() 误操作）
  const rawText = String(text).trim() === "" ? " " : text;
  const textWidth = calculateTextWidth(rawText, fontStyle);

  // 根据 disableOffset 标志决定偏移量
  const dynamicWidth = disableOffset ? textWidth : textWidth + offset;
  const minThreshold = disableOffset ? minWidth : minWidth + offset;

  return Math.max(dynamicWidth, minThreshold);
};
const dynamicWidthOffset = computed(() => {
  return `${getDynamicWidth({ text: props.title })}px`;
});
const dynamicWidth = computed(() => {
  return `${getDynamicWidth({ text: props.title, offset: -20 })}px`;
});
const dynamicWidthTitle = computed(() => {
  return `${getDynamicWidth({ text: props.title, offset: 25 })}px`;
});
</script>

<template>
  <div class="modpx-wrapper" :style="{ width: dynamicWidthOffset }">
    <div class="modpx-title">
      <div class="flex w-[100%] items-center mb-[3px]">
        <div class="flex w-[100%] justify-between">
          <div class="modpx-title-content" :style="{ width: dynamicWidthTitle }">
            <ReTextTooltip v-if="groupName" :style="{ 'white-space': 'nowrap' }" :content="`${groupName}`" />

            <template v-else>
              <ReTextTooltip :style="{ 'white-space': 'nowrap' }" :content="`${title}`" />
              <ReTextTooltip :style="{ 'white-space': 'nowrap' }" :content="`${code}`" />
            </template>
          </div>
          <px-button type="primary" link size="small" @click="openCharline">数据分析</px-button>
        </div>
      </div>
    </div>
    <px-scrollbar max-height="115px" always>
      <div v-if="contentList?.length > 0" class="flex flex-col w-[100%]">
        <div
          v-for="(item, index) in contentList"
          :key="item.tagNum ? item.tagNum : index"
          class="flex items-center justify-between w-[100%] mt-[6px]"
        >
          <div class="text-[12px] text-[rgba(0,0,0)]" :style="{ width: dynamicWidth }">
            <ReTextTooltip :key="index" :style="{ 'white-space': 'nowrap', width: dynamicWidth }" :content="item.title" />
          </div>
          <div class="w-[90px] pl-[5px] flex text-[12px]">
            <span class="text-[#3B82F6]">{{ convertStringToNumber(item.value) }}</span>
            <span class="text-[rgba(0,0,0)]">{{ item.unit }}</span>
          </div>
        </div>
      </div>
      <px-empty v-else description="暂无数据" :image-size="80" style="padding: 16px 0" :image="empty" />
    </px-scrollbar>
  </div>
</template>

<style lang="scss" scoped>
.modpx-wrapper {
  position: absolute;
  top: -35px;
  left: 28px;
  // width: 200px;
  padding: 8px;
  margin-bottom: 2px;
  background: rgb(255 255 255 / 75%);
  backdrop-filter: blur(10px);
  border-radius: 8px;

  .content-wrapper {
    overflow: hidden;
  }

  .modpx-title {
    display: flex;
    align-items: center;
    min-height: 13px;
    font-size: 13px;
    font-weight: 700;
    line-height: 13px;
    color: #000;
    box-shadow: inset 0 -1px 0 0 rgb(0 0 0 / 10%);

    &-content {
      display: flex;
      flex-direction: column;
      // width: 140px;
      width: auto;
      height: auto;
    }
  }
}
</style>
